package com.mvc.business.user.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
@RequestMapping("/upload")
public class UploadController {
	/**
	 * 普通上传 
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/upload")//uploadfile为上传文件控件的name
	public String upload(@RequestParam("uploadfile")CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		System.out.println(file.getSize() + "  " + file.getOriginalFilename());
		//将文件保存到E盘
		try {
			FileOutputStream fos = new FileOutputStream("E:\\" + new Date().getTime() + file.getOriginalFilename());
			InputStream is = file.getInputStream();
			int x = 0;
			while ((x = is.read()) != -1) {
				fos.write(x);
			}
			is.close();
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "/upload//upload";
	}
	@RequestMapping("/mvcupload")
	public String mvcUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getSession().getServletContext());
		if(cmr.isMultipart(request)){
			MultipartHttpServletRequest msr = (MultipartHttpServletRequest)request;
			Iterator<String> iter = msr.getFileNames();
			while (iter.hasNext()) {
				MultipartFile mFile = msr.getFile((String)iter.next());
				if(mFile != null){
					//上传文件
					String fileName = mFile.getOriginalFilename();
					String path = "E:\\" + fileName;
					File f = new File(path);
					mFile.transferTo(f);
				}
			}
		}
		return "/upload/upload";
	}
}
